<?php

use Core\API_Controller;
use Models\OAuth2Client;
use Models\User;
use OAuth2\ResponseType\AccessToken;
use OAuth2\Storage\Redis;
use Libraries\OAuth2Client\OAuth2ClientFactory;

class LoginController extends API_Controller
{
	public function index()
	{
		$user = new User();
		$this->load->library('form_validation');
		$this->form_validation->set_rules('phone', '手机号', [
			'required',
			'exist[users.phone]'
		])
		->set_rules('password', '密码', 'required');
		if ($this->form_validation->run()) {
			$user = User::where('phone', $this->input->post('phone'))->get_one();
			$user->update($user['id'], [
				'update_at' => date('Y-m-d H:i:s')
			]);
			
			if (!$user->verify($this->input->post('password'))) {
				return $this->validateError('password', '密码不正确');
			}

			// $access_token = $user->CreateSystemAccessToken();
			// return $this->response($access_token);
            $this->session->authUser = $user;
            return $this->success();
		} else {
			return $this->validateError($this->form_validation->error_array());
		}
	}

	public function wechat()
    {
        $client = OAuth2ClientFactory::createClient('wechat');
        $state = 3412;
        $this->session->wechatState = $state;
        $this->session->loginType = 'wechat';
        $client->redirectToAuthorize(CONFIG('wechat.mp.redirectUri'), $this->session->wechatScope ?: 'snsapi_base', $state);
    }

	public function callback()
    {
        $allowed = in_array($this->session->loginType, array('wechat'));
        if (!$allowed) {
            echo '不支持的登录类型';exit;
        }

        $client = OAuth2ClientFactory::createClient($this->session->loginType);
        if ($client->getCode()) {
            $access_token = $client->getAccessToken($client->getCode());
            $user = new User();
            if ($this->session->loginType == 'wechat' && $this->session->wechatScope != 'snsapi_userinfo') {
                if (!$user->where('openid_weixin', $access_token['user_id'])->get_one()) {
                    $this->session->wechatScope = 'snsapi_userinfo';
                    redirect('api/login/wechat');
                }
            }


            $userInfo = $client->getUserInfo($access_token['access_token']);

            $user = $client->saveUser($user, $userInfo);

            $user = (new User)->find($user['id']);

            $user->login();
            $user->update();

            $this->session->authUser = $user->toArray();

            redirect('http://rcbao.1qiao.com/frontend/index.html?login=1');
        } else {
            // 用户未授权
            show_error('您未授权，无法使用');
            // return $this->load->view('unAuthorized');
        }
    }
}
